package com.tidc.authentication.config;

import com.tidc.authentication.mapper.UserMapper;
import com.tidc.authentication.pojo.Student;
import com.tidc.authentication.pojo.Teacher;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

/**
 * @ClassNmae MyUserDeatisService
 * @Description TODO
 * @Author 14631
 **/
@Component
@CrossOrigin //解决跨域问题
public class MyUserDeatisService implements UserDetailsService{
	@Autowired
	private UserMapper userMapper;
	@Autowired
	ClientDetailsService clientDetailsService;
	@Override
	public UserDetails loadUserByUsername(String email) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
		if(authentication==null){
			ClientDetails clientDetails = clientDetailsService.loadClientByClientId(email);
			if(clientDetails!=null){
				//密码
				String clientSecret = clientDetails.getClientSecret();
				return new User(email,clientSecret,AuthorityUtils.commaSeparatedStringToAuthorityList(""));
			}
		}
		System.out.println(email+"登录了!!!!!");
		Student student = userMapper.selectStudent(email.trim());
		Teacher teacher = userMapper.selectTeacher(email);
		String power = "ROLE_STUDENT,ROLE_User";
		if(student!=null) {
			System.out.println(student);
			return returnUser(student.getEmail(),student.getPassword(),power);
		}
		if(teacher!=null){
			//这个return的user是spring的
			System.out.println(teacher);
			power = "ROLE_TEACHER,ROLE_STUDENT,ROLE_User";
			return returnUser(teacher.getEmail(),teacher.getPassword(),power);
		}

		return returnUser(student.getEmail(),student.getPassword(),power);

	}
	public User returnUser(String email,String password,String power){
		return new User(email,password,
				true,true,true,true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(power));
	}

}
